package cn.ibizlab.odoo.activiti.service.impl;

import cn.ibizlab.odoo.activiti.entity.TaskInfo;
import cn.ibizlab.odoo.activiti.service.ITaskService;
import cn.ibizlab.odoo.activiti.util.TaskUtil;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.DelegationState;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.Map;


@Service
public class TaskServiceImpl implements ITaskService {

	@Autowired
	TaskService taskService;

	@Autowired
	TaskUtil taskUtil;

	/**
	 * 完成任务
	 * @param taskId
	 * @param variables
	 * @return
	 */
	public String complete(String taskId, Map variables) {

		if (StringUtils.isEmpty(taskId)) {
			return "param error";
		}

		try {
//			// 设置流程参数（单）
//			taskService.setVariable(taskId, key, value);
			// 设置流程参数（多）
			taskService.setVariables(taskId, variables);

			// 若是委托任务，请先解决委托任务
			Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
			if (DelegationState.PENDING.equals(task.getDelegationState())) {
				return "resolve delegation first";
			}
			taskService.complete(taskId);
			System.out.println("任务完成");
			System.out.println("任务ID:" + taskId);
			System.out.println("任务处理结果:" + variables);
			System.out.println("*****************************************************************************");
		} catch (Exception e) {
			return "fail";
		}
		return "success";
	}

	/**
	 * 查询当前任务
	 * @param processInstanceId
	 * @return
	 */
	public TaskInfo getCurentTask(String processInstanceId) {

		Task task;
		TaskInfo taskInfo =null;
		if (StringUtils.isEmpty(processInstanceId)) {
			return taskInfo;
		}

		try {
			 task = taskService.createTaskQuery()// 创建查询对象
					.processInstanceId(processInstanceId)// 通过流程实例id来查询当前任务
					.singleResult();// 获取单个查询结果



			if (task == null) {
				System.out.println("流程已结束");
				System.out.println("流程实例ID:" + processInstanceId);
				System.out.println("*****************************************************************************");
				return taskInfo;
			}

			taskInfo=taskUtil.covert2Task(task);

			System.out.println("任务ID:" + taskInfo.getId());
			System.out.println("任务名称:" + taskInfo.getName());
			System.out.println("任务的创建时间:" + taskInfo.getCreateTime());
			System.out.println("任务的办理人:" + taskInfo.getAssignee());
			System.out.println("流程实例ID：" + taskInfo.getProcessInstanceId());
			System.out.println("执行对象ID:" + taskInfo.getExecutionId());
			System.out.println("流程定义ID:" + taskInfo.getProcessDefinitionId());
			System.out.println("*****************************************************************************");


		} catch (Exception e) {
			return taskInfo;
		}


		return taskInfo;
	}
}
